//
//  SettingViewController.m
//  JiuKuGospel
//
//  Created by jiukuyinyue on 15-8-11.
//  Copyright (c) 2015年 JiuKuForApp. All rights reserved.
//

#import "SettingViewController.h"
#import "AboutJiukuViewController.h"
//#import "JKSettingCell.h"
#import "JKSleepTimeCell.h"
#import "SetHelper.h"
#import "SettingViewController+ClearCache.h"

#import "JPUSHService.h"

@interface SettingViewController ()<UITableViewDataSource, UITableViewDelegate, MBProgressHUDDelegate>
{
    MBProgressHUD *HUD;
    MBProgressHUD *HUDLod;
}
@property (nonatomic, strong)NSMutableArray * allArr;
@property (nonatomic, strong)UISwitch * setSwitch;

@property (nonatomic, strong)UILabel * exitLabel;
@end

@implementation SettingViewController


- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //导航栏字体颜色
    self.title = @"设置";
    
    [self createUI];
}
- (void)leftBtnAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)createUI {
    //用户未登录
    if([[_UserM usercode] isEqualToString:@""]){
        self.allArr = [NSMutableArray arrayWithObjects: @"2G/3G/4G流量提醒", @"清除缓存", @"关于九酷福音",@"用户反馈", nil];
        
    }else{
        self.allArr = [NSMutableArray arrayWithObjects: @"个人信息",@"2G/3G/4G流量提醒", @"清除缓存", @"关于九酷福音",@"用户反馈", nil];
    }
     self.setTab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStylePlain];
    _setTab.scrollEnabled = NO;
    _setTab.delegate = self;
    _setTab.dataSource = self;
    self.setTab.estimatedRowHeight = 0;
    self.setTab.estimatedSectionHeaderHeight = 0;
    self.setTab.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_setTab];
    [self setExtraCellLineHidden:_setTab];
    //cell分割线顶头
    if ([self.setTab respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.setTab setSeparatorInset: UIEdgeInsetsZero];
    }
    if ([self.setTab respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.setTab setLayoutMargins: UIEdgeInsetsZero];
    }
    
    self.setSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 75, 15, 40, 30)];
    _setSwitch.onTintColor = JK_RED_COLOR;
    [_setSwitch addTarget:self action:@selector(wifiChanging:) forControlEvents:UIControlEventValueChanged];
 
     self.huanCunLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 60-30, 15, 60, 30)];
     _huanCunLabel.font = [UIFont systemFontOfSize:14];
    _huanCunLabel.textAlignment = NSTextAlignmentLeft;
    _huanCunLabel.textColor = [UIColor grayColor];
    _huanCunLabel.text = [self readCacheSize];

    self.exitLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 50)];
    _exitLabel.text = @"退出登录";
    _exitLabel.textAlignment = NSTextAlignmentCenter;
    _exitLabel.backgroundColor = [UIColor whiteColor];
    _exitLabel.textColor = titleColorLSZ;
    if (ScreenWidth == 320) {
        //5
        _exitLabel.font = FONT_(13.5);
    }else if(ScreenWidth == 375){
        // 6 7
        _exitLabel.font = FONT_(14);
    }else {
        //plus
        _exitLabel.font = FONT_(14.5);
    }
}
- (void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark - setTab代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (![[_UserM usercode] isEqualToString:@""]) {
        return 2;
    }
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return _allArr.count;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 30;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return 50;
    }
    return 60;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellStr = @"setCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellStr];
    }
    cell.textLabel.text = [_allArr objectAtIndex:indexPath.row];
    cell.textLabel.textColor = JK_BLACK_COLOR;
    if (indexPath.section == 0)
    {
        if ((indexPath.row == 1&& ![[_UserM usercode] isEqualToString:@""] ) || (indexPath.row == 0&& [[_UserM usercode] isEqualToString:@""] ))
        {
            //流量
            [cell addSubview:_setSwitch];
            NSString * document = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];
            NSString * onlyWifi = [document stringByAppendingPathComponent:@"onlyWifiFile"];
            NSDictionary * wifiDic = [NSDictionary dictionaryWithContentsOfFile:onlyWifi];
            if ([[wifiDic objectForKey:@"isONOrOff"] isEqualToString:@"ON"]) {
                _setSwitch.on = YES;
                [SetHelper shareSetHelper].isOnOrOFF = YES;
            }else if ([[wifiDic objectForKey:@"isONOrOff"] isEqualToString:@"OFF"]) {
                _setSwitch.on = NO;
                [SetHelper shareSetHelper].isOnOrOFF = NO;
            }else{
                _setSwitch.on = YES;
                [SetHelper shareSetHelper].isOnOrOFF = YES;
            }
            
        }else{
            UIImageView * tempImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 30, (60-12)/2, 7, 12)];
            NSString * imageStr = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"zhishi%@", [TheHomeManager shareTheHomeManager].iPhone23] ofType:@"png"];
            
            tempImageView.image = [UIImage imageWithContentsOfFile:imageStr];
            [cell addSubview:tempImageView];
            if ((indexPath.row == 2&& ![[_UserM usercode] isEqualToString:@""] ) || (indexPath.row == 1&& [[_UserM usercode] isEqualToString:@""] )) {
                [cell addSubview:_huanCunLabel];
            }
        }
    }
    if (indexPath.section == 1) {
        cell.textLabel.text = @"";
        [cell addSubview:self.exitLabel];
    }
    if (ScreenWidth == 320) {
        //5
        cell.textLabel.font = FONT_(13.5);
    }else if(ScreenWidth == 375){
        // 6 7
        cell.textLabel.font = FONT_(14);
    }else {
        //plus
        cell.textLabel.font = FONT_(14.5);
    }
    cell.textLabel.textColor = titleColorLSZ;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0){
        if((indexPath.row == 0 && ![[_UserM usercode] isEqualToString:@""])){
            LSZPersonalInformationVC * vc = [[LSZPersonalInformationVC alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        if ((indexPath.row == 2 && ![[_UserM usercode] isEqualToString:@""]) || (indexPath.row == 1 && [[_UserM usercode] isEqualToString:@""])) {
            [self clearCache];
        }
        if ((indexPath.row == 3 && ![[_UserM usercode] isEqualToString:@""]) || (indexPath.row == 2 && [[_UserM usercode] isEqualToString:@""]) ) {
            //关于
            AboutJiukuViewController * aboutVC = [[AboutJiukuViewController alloc] init];
            [self.navigationController pushViewController:aboutVC animated:YES];
        }
        if ((indexPath.row == 4&& ![[_UserM usercode] isEqualToString:@""]) || (indexPath.row == 3 && [[_UserM usercode] isEqualToString:@""]) ) {
            //用户反馈
            SuggestMessageViewController * suggestVC = [[SuggestMessageViewController alloc] init];
            [self.navigationController pushViewController:suggestVC animated:YES];
        }
    }
    //退出登录
    if (indexPath.section == 1) {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"确定退出登录?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = 501;
        [alertView show];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 30)];
    tempView.backgroundColor = [UIColor whiteColor];
    UIView * lineTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 0.5)];
    lineTop.backgroundColor = JK_HUISE_COLOR;
    [tempView addSubview:lineTop];

    UIView * lineBottom = [[UIView alloc] initWithFrame:CGRectMake(0, tempView.height-0.5, self.view.width, 0.5)];
    lineBottom.backgroundColor = JK_HUISE_COLOR;
    [tempView addSubview:lineBottom];
    return tempView;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 501) {
        if (buttonIndex == 1) {
            //清空一些数据  此处先都删除了
//            [[UserPageManager shareUserPageManager] clearUserMessages];
//            [UserPageManager shareUserPageManager].isLogin = NO;
//            
//            [UserPageManager shareUserPageManager].userPageVC.userNameLabel.hidden = YES;
//            [UserPageManager shareUserPageManager].userPageVC.loginBtn.hidden = NO;
//            _UserM.usercode = @"";//清除缓存的数据
            self.allArr = [NSMutableArray arrayWithObjects: @"2G/3G/4G流量提醒", @"清除缓存", @"关于九酷福音",@"用户反馈", nil];

            [_UserM setUsercode:@""];//清除缓存的数据
            [_UserM setSys_not_read:@""];
            [_UserM setMsg_not_read:@""];
            //headerPhoto
            NSString * State = NullStringjudgment([[NSUserDefaults standardUserDefaults]objectForKey:@"headerPhoto"]);
            [[SDImageCache sharedImageCache] removeImageForKey:State withCompletion:^{
                NSLog(@"111");
            }];
            //退出的时候删除别名
            [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                if (iResCode == 0) {
                    NSLog(@"删除别名成功");
                }
            } seq:1];
//            NSUserDefaults * userDefaults = [NSUserDefaults  standardUserDefaults];
//            [userDefaults removeObjectForKey:@"headerPhoto"];
//            [userDefaults removeObjectForKey:@"uid"];
//            [userDefaults removeObjectForKey:@"homePage"];
//            [userDefaults   synchronize];
            NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
            [SVProgressHUD showSuccessWithStatus:@"账号已成功退出!"];
            [_setTab reloadData];
            [SVProgressHUD dismissWithDelay:1];
        }
    }
}
- (void)myProgressTask {
    
    float progress = 0.0f;
    while (progress < 1.0f) {
        progress += 0.01f;
        HUD.progress = progress;
        usleep(30000);
    }
    __block UIImageView *imageView;
    dispatch_sync(dispatch_get_main_queue(), ^{
        UIImage *image = [UIImage imageNamed:@"Checkmark"];
        imageView = [[UIImageView alloc] initWithImage:image];
    });
    HUD.customView = imageView;
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.label.text = @"删除完成！";
    sleep(2);
}

//寻找缓存路径
- (NSString *)filePath:(NSString *)file
{
    NSString * docouments = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];
    NSString * filePath = [docouments stringByAppendingPathComponent:file];
    NSLog(@"路径----%@", filePath);
    return filePath;
}
#pragma mark - 设置 仅Wi-Fi联网方法
- (void)wifiChanging:(UISwitch *)setSwitch
{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode=MBProgressHUDModeText;//枚举类型不同的效果


    if (setSwitch.on == YES) {
        _setSwitch.on = YES;
        [SetHelper shareSetHelper].isOnOrOFF = YES;
        NSString * document = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];
        NSString * onlyWifi = [document stringByAppendingPathComponent:@"onlyWifiFile"];
        NSDictionary * wifiDic = [NSDictionary dictionaryWithObjectsAndKeys:@"ON", @"isONOrOff", nil];
        [wifiDic writeToFile:onlyWifi atomically:YES];
        hud.label.text=@"流量提醒已开启";

        //Change the host name here to change the server you want to monitor.
        
    }else{
        _setSwitch.on = NO;
        [SetHelper shareSetHelper].isOnOrOFF = NO;
        NSString * document = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];
        NSString * onlyWifi = [document stringByAppendingPathComponent:@"onlyWifiFile"];
        NSDictionary * wifiDic = [NSDictionary dictionaryWithObjectsAndKeys:@"OFF", @"isONOrOff", nil];
        [wifiDic writeToFile:onlyWifi atomically:YES];
        hud.label.text=@"流量提醒已关闭";
    }
    [self performSelector:@selector(removeMB) withObject:nil afterDelay:1.0];
}
- (void)removeMB
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

@end
